<template>
	<view class="works">
		<view class="works-top">
			<p>{{works_user}}的智配作品</p>
			<image :src="img_top" mode=""></image>
		</view>
		
		<view class="works-goods">
			<u-divider text="单品列表"  textPosition="left" class="goods-title">单品列表</u-divider>
			<scroll-view class="allgoods" :scroll-y="true">
				<view class="goods-for" v-for="shop in shop_list" :key="shop.id">
					<div class="for-image">
						<image :src="shop.cover_pic" mode=""></image>					
						
					</div>
					
					<div class="for-duce">
						<h5>{{shop.name}}</h5>
						<div class="cart">
							<p><span>￥</span>{{shop.price}} <span>/{{shop.unit}}</span> </p>
							<div class="cart_icon" @click="handleToCard(shop)">
								<i class="iconfont icon-cart-full"></i>
							</div>
						</div>
						
					</div>
				</view>
			</scroll-view>
			
			<u-divider text="没有更多数据了" :hairline="true" style="margin: 30rpx 0;">没有更多数据了</u-divider>
		</view>
		
	<newSkuPopup
	  ref="skuPopup"
	  :finalmsg="finalmsg"
	  :shopmsg="shopmsg"
	  :subIndex="subIndex"
	  :shopimg="shopimg"
	  :skuText="skuText"
	  :diyTemplates="templates"
	  @closeSkuPopup="closeSkuPopup"
	  @setSelectNum="setSelectNum"
	   @selectPushData="selectPushData"
	   @buyNow="confirmBuy"
	></newSkuPopup>	
	</view>
</template>

<script>
	import newSkuPopup from "../components/skuPopup.vue";
	export default {
		components: {		
		  newSkuPopup,
		},
		data() {
			return {
				works_id:'',
				shop_list:[],
				img_top:'',
				templates: [],
				shopmsg: null, //商品信息
				finalmsg: null, //选取规格后的商品数量，以及是否为会员价格信息
				subIndex: [], //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
				shopimg: "", //选择商品规格时的商品图片
				value:1,// sku选择的数量
				id:'',//商品id
				attr:[],//规格组
				selectArr:[],//存放被选中的值
				shopItemInfo: {}, //存放要和选中的值进行匹配的数据
				goodsInfoNew: {}, //当规格选择完成时重新覆盖商品信息
				skutitlename: "", //提示用户例如：请选择温度，口味；或者提示用户已选择温度，口味
				skutitlenamelist: [], //存储规格标题
				skuId: "", //规格id
				works_user:'',//作品作者
			};
		},
		onLoad(options){
			this.works_id=options.id;
			this.getShops()
		},
	 computed:{
		skuText() {
		  if (this.skuId != "") {
		    let str = [];
		    this.skuId.forEach((item) => {
		      str.push(item.attr_name);
		    });
		    return str.join(",");
		  } else {
		    return this.$t("diy.sku");
		  }
		}, 
	 },
		methods:{
			confirmBuy() {		 
			    this.addCart();

			},
			// 判断库存是否为0
			isMay(result) {
			  for (var i in result) {
			    if (result[i] == "") {
			      return true;
			    }
			  }
			  result = result.join("_");
			  if (!this.shopItemInfo[result]) {
			    return false;
			  }
			  return this.shopItemInfo[result].num == 0 ? false : true;
			   
			},
			//通过选取规格获取该规格下的商品准确价格
			getPriceNum(arrt_list) {
			  if (this.activity_new_user_id) {
			    let ids = arrt_list.join(","),
			      attr = this.shopmsg.attr;
			
			    for (let i = 0; i < attr.length; i++) {
			      let item = attr[i].attr_list.map((el) => el.attr_id).join(",");
			      if (ids === item) {
			        this.finalmsg = attr[i];
			        break;
			      }
			    }
			    return;
			  }
			
			  var params = {
			    goods_id: this.shopmsg.id,
			    attr_list: arrt_list,
			    number: this.value,
			  };
			  try {
			    params.attr_list = JSON.stringify(params.attr_list);
			    this.$allrequest.goods.goodsAttrInfo(params).then((res) => {
			      if (res.code == 0) {
			        this.finalmsg = res.data;
			      }
			    });
			  } catch (e) {
			  }
			},
			//获取选定的值
			getInfo(item) {
			  var checked = item.join("_");
			  if (this.shopItemInfo[checked]) {
			    this.goodsInfoNew = this.shopItemInfo[checked];
			    this.skutitlename =
			      this.$t("common.choosed") +
			      "：" +
			      this.shopItemInfo[checked].supplier_price;
			    this.skuId = this.shopItemInfo[checked].attr_list;
			  } else {
			    this.goodsInfoNew = {};
			    var skutitle = [];
			    for (var i = 0; i < this.skutitlenamelist.length; i++) {
			      if (this.skutitlenamelist[i]) {
			        skutitle.push(this.skutitlenamelist[i]);
			      }
			    }
			    this.skutitlename =
			      this.$t("common.noChoose") + " " + skutitle.toString(",");
			    this.skuId = "";
			  }
			  if (this.skuId) {
			    this.arrt_list = [];
			    for (var i = 0; i < this.skuId.length; i++) {
			      this.arrt_list.push(this.skuId[i].attr_id);
			    }
			    this.arrt_list.join(",");
			    this.getPriceNum(this.arrt_list);
			  }
			},
			//处理数据
			checkItem() {
			  var option = this.shopmsg.attr_group_list;
			  var result = []; //定义数据存储被选中的值)
			  for (let i = 0; i < option.length; i++) {
			    result[i] = this.selectArr[i] ? this.selectArr[i] : "";
			  }
			  for (let i = 0; i < option.length; i++) {
			    var last = result[i];
			    for (var k = 0; k < option[i].attr_list.length; k++) {
			      result[i] = option[i].attr_list[k].attr_id;
			      option[i].attr_list[k].isShow = this.isMay(result);
			    }
			    result[i] = last;
			  }
			  this.shopmsg.attr_group_list = [];
			  this.$set(this.shopmsg, "attr_group_list", option);
			
			  this.getInfo(this.selectArr);
			},
			pushData(id, pindex, index, disable, attr_group_id) {
			  if (!disable) {
			    return "";
			  }
			  if (this.selectArr[pindex] != id) {
			    this.selectArr[pindex] = id;
			    this.subIndex[pindex] = index;
			    this.skutitlenamelist[pindex] = "";
			    this.attr[pindex] = {
			      attr_id: id,
			      attr_group_id: attr_group_id,
			    };
			  }
			  this.checkItem();
			},
			selectPushData(e) {
			  let { id, pindex, index, disable, attr_group_id } = { ...e };
			  this.pushData(id, pindex, index, disable, attr_group_id);
			},
			setSelectNum(e) {
			  this.value = e;
			},
			addCart(){
				if (!this.$refs.skuPopup.showSkuPopup) {
				  this.$refs.skuPopup.showPopup();
				  return;
				}
				if (this.finalmsg == "" || this.finalmsg == undefined) {
				  uni.showToast({
				    title: this.$t("diy.sku"),
				    icon: "none",
				  });
				  return;
				}
				if (this.value > this.finalmsg.num || this.value > this.shopmsg.num) {
				  uni.showToast({
				    title: this.$t("diy.stock"),
				    icon: "none",
				  });
				  return;
				}
				this.$allrequest.goods
				  .addCart({
				    goods_id: this.id,
				    attr: JSON.stringify(this.attr),
				    num: this.value,
				  })
				  .then((res) => {
				    this.show = !this.show;
				    if (res.code == 0) {
				      uni.showToast({
				        title: res.msg,
				        icon: "none",
				      });
				      // 加购成功后，关闭sku弹框
				      this.closeSkuPopup();
				    } else {
				      uni.showToast({
				        title: res.msg,
				        icon: "none",
				      });
				    }
				  })
				  },
		    async getShops(){
				const res=await this.$allrequest.collocation.shareAfter({
					id:this.works_id
				})
		  this.img_top=res.data.works.image;
		  this.shop_list=res.data.goods_list;
		  this.works_user=res.data.works.user_name;
			},
			// 关闭sku弹框
			closeSkuPopup() {
			  this.$refs.skuPopup.hidePopup();
			},
			// 点击购物车按钮
			handleToCard(obj) {		
			  const isLogin = this.$utils.isLogin();
			  if (!isLogin) return;
			  this.shopmsg=obj;
			  this.shopimg=obj.cover_pic;
			  if(this.shopmsg){
				  this.$refs.skuPopup.attrArr=JSON.parse(JSON.stringify(this.shopmsg.attr_group_list));
			  }
			  this.id=obj.id;
			  var isarr=this.shopmsg.attr instanceof Array;
			  if(!isarr){
				 		  this.shopmsg.attr=JSON.parse(this.shopmsg.attr); 
			  }
	
			 // if (this.shopmsg.pic_list.length != 0) {
			 //   if (this.shopmsg.pic_list[0].type != "video") {
			 //     this.shopimg = this.shopmsg.pic_list[0].pic_url;
			 //   } else {
			 //     if (this.shopmsg.pic_list.length > 1) {
			 //       this.shopimg = this.shopmsg.pic_list[1].pic_url;
			 //     }
			 //   }
			 // }
			  for (var i of this.shopmsg.attr) {
			    var sp = "";
			    for (var j of i.attr_list) {
			      sp += j.attr_id + "_";
			    }
			    if (sp.length > 0) {
			      sp = sp.substr(0, sp.length - 1);
			    }
			    this.shopItemInfo[sp] = i;
			  }
			  for (var m of this.shopmsg.attr_group_list) {
			    this.skutitlenamelist.push(m.attr_group_name);
			  }
			  this.checkItem();
			  // if (this.goodsDisabled.no_num || this.goodsInfo.out_line) return;
			  if (obj.is_negotiable == 1) {
			    let mdLocalData = uni.getStorageSync("storeMdData");
			    let mobile = "";
			    if (mdLocalData) {
			      mdLocalData = JSON.parse(mdLocalData);
			      if (mdLocalData.mobile) {
			        mobile = mdLocalData.mobile;
			      }
			    } else {
			      mobile = this.stores.mobile;
			    }
			    if (!mobile) {
			      uni.showToast({
			        title: this.$t("diy.noPhone"),
			        icon: "none",
			        duration: 2000,
			      });
			      return;
			    }
				this.$utils.makePhoneCall(mobile);

			    return;
			  }
			  this.addCart(obj);
			},
		}	
	}
</script>

<style lang="scss">
.works{
	width: 100vw;
	height: 100vh;
	padding: 0 40rpx;
	.works-top{
		overflow: hidden;
		margin-bottom:30rpx;
		p{
			font-weight: bold;
			margin: 30rpx 0;
		}
		image{
			width: 100%;
			height: 300rpx;
		}
	}
	.works-goods{
		display: flex;
		flex-direction: column;
		align-items: center;
		/deep/.goods-title{
			margin: 20rpx;
		}
		.allgoods{
			display: flex;
			flex-direction: column;
			align-items: center;
			.goods-for{
				width:100%;
				display:flex;
				border:2rpx solid #ddd;
				border-radius: 10rpx;
				.for-image{
					image{
						width:200rpx;
						height:200rpx;
						display:block;
						border-radius: 10rpx 0 0 10rpx;
					}
				}
				.for-duce{
					padding:20rpx;
					flex-grow: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					h5{
						font-size: 40rpx;
						font-weight: bold;
					}
					.cart{
						width:100%;
						display: flex;
						justify-content: space-between;
						align-items: center;
						p{
							color: #D02502;
							font-size: 36rpx;
							font-weight: bold;
							display: flex;
							align-items: baseline;
							span{
								&:first-child{
									color:#D02502;
									font-size: 24rpx;
								}
								&:last-child{
									color: gray;
									font-size: 24rpx;
								}
							}
						}
						.cart_icon{
							width: 60rpx;
							height: 60rpx;
							border-radius: 50%;
							background: #D02502;
							display: flex;
							justify-content: center;
							align-items: center;
							i{
								color: white;
								font-size:50rpx
							}
						}
					}
				}
			}
		}
	}
}
</style>
